package broker

import (
	"context"
	"fmt"
	"gitlab.local/backend/proto/dto"
	"ota/bll"
	"ota/client/grpc"
	log "ota/collector/logger"
	"strings"
	"time"
)

var ControlReport = &controlReport{}

// controlHandler 中控上报
type controlReport struct {
}

// HandlerControl 中控上报
func (a *controlReport) HandlerControl(data *dto.Controller) (err error) {

	var (
		errMessage  []string
		infoMessage []string
		ctx, _      = context.WithTimeout(context.Background(), time.Minute*5)
	)

	defer func() {

		var (
			logger  = log.Info
			message = infoMessage
			result  = "SUCCESS"
		)
		if errMessage != nil {
			logger = log.Error
			result = "FAILED"
			message = append(message, errMessage...)
		}

		logger(fmt.Sprintf("【 HandlerControl Request:(sn:%+v,version:%+v) Result:%v 】%v",
			data.Sn, data.FirmwareVersion, result, strings.Join(message, " ")))
	}()

	oldControl, err := grpc.EBikeControls.UpdateControl(ctx, &dto.ControlInfoRequest{SnCode: data.Sn, FirmwareVersion: data.FirmwareVersion})
	if err != nil {
		errMessage = append(errMessage, fmt.Errorf("update control info error:%v", err).Error())
		return err
	}

	//版本检测，升级版本
	if len(data.FirmwareVersion) > 0 && len(data.Sn) > 0 {

		/* 可以升级或者降级,不可以平级 */
		if oldControl.FirmwareVersion == data.FirmwareVersion {
			infoMessage = append(infoMessage, fmt.Sprintf("check firmware version no change"))
			return nil
		}

		if err = bll.Ota.CheckUpgradeResult(data); err != nil {
			errMessage = append(errMessage, fmt.Errorf("check upgrade result error:%v", err).Error())
		} else {
			infoMessage = append(infoMessage, fmt.Sprintf("check upgrade result success"))
		}
	}

	return err
}
